<?php

if (!defined('IN_SYS'))
    exit('Access Denied');

class import_controller extends admincp {

    public $error = [];

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        require self::tpl("import");
    }

    public function uploads() {
        $time = time();
        $config = array(
            "pathFormat" => "/data/temp/{time}{rand:6}",
            "maxSize" => 2048000,
            "allowFiles" => array('.xls', '.xlsx'),
        );
        $up = new uploader('file', $config, 'upload');
        $data = $up->getFileInfo();
        $suc = 0;
        $error = 0;
        if (!empty($data) && $data['state'] == "SUCCESS") {
            $file = ROOT . $data['url'];
            if (is_file($file)) {
                $excel = new PHPExcel();
                try {
                    $inputFileType = PHPExcel_IOFactory::identify($file);
                    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
                    $objPHPExcel = $objReader->load($file);
                } catch (Exception $e) {
                    die("加载文件发生错误：" . $e->getMessage());
                }

                // 确定要读取的sheet，什么是sheet，看excel的右下角，真的不懂去百度吧
                $sheet = $objPHPExcel->getSheet(0);
                $highestRow = $sheet->getHighestRow();
                $highestColumn = $sheet->getHighestColumn();

                // 获取一行的数据
                for ($row = 2; $row <= $highestRow; $row++) {
                    // Read a row of data into an array
                    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
                    //这里得到的rowData都是一行的数据，得到数据后自行处理，我们这里只打出来看看效果
                    $res = $this->checkdata($rowData, $row);
                    if ($res) {
                        mredis::lPush('queue_improt_yuming', json_encode($res));
                        $suc++;
                    } else {
                        $error++;
                    }
                }
                $this->respone_json(array('suc' => $suc, 'error' => $error, 'error_tips' => $this->error));
            } else {
                $this->respone_json('找不到文件');
            }
        } else {
            $this->respone_json($data['state']);
        }
    }

    protected function checkdata($data, $row) {
        if (empty($data[0])) {
            return false;
        }
        $res = $data[0];
        $result = [];
        if (!empty($res[0]) && $this->checkWebSite($res[0], $row)) {
            $result['name'] = $res[0];
        } else {
            $this->error[$row][] = '没找到域名';
            return false;
        }
        if (!empty($res[1])) {
            $result['sitename'] = trim($res[1]);
        } else {
            $this->error[$row][] = '网站名称不能为空';
            return false;
        }

        if (!empty($res[2])) {
            $result['siteTitle'] = trim($res[2]);
        } else {
            $this->error[$row][] = '首页TITLE不能为空';
            return false;
        }

        if (!empty($res[3])) {
            $result['keywords'] = trim($res[3]);
        } else {
            $this->error[$row][] = '关键词不能为空';
            return false;
        }
        if (!empty($res[4])) {
            $result['description'] = trim($res[4]);
        } else {
            $this->error[$row][] = '描述不能为空';
            return false;
        }
        if (!empty($res[5]) && ($res[5] == '是' || $res[5] == 1)) {
            $result['seoTitle'] = 1;
        } else {
            $result['seoTitle'] = 0;
        }

        if (!empty($res[5]) && ($res[5] == '是' || $res[5] == 1)) {
            $result['seoTitle'] = 1;
        } else {
            $result['seoTitle'] = 0;
        }

        if (!empty($res[5]) && ($res[5] == '是' || $res[5] == 1)) {
            $result['seoTitle'] = 1;
        } else {
            $result['seoTitle'] = 0;
        }

        if (!empty($res[6]) && in_array(intval($res[6]), array(1, 2, 3))) {
            $result['seoTitlex'] = intval($res[6]);
        } else {
            $result['seoTitlex'] = 1;
        }

        if (!empty($res[7])) {
            $result['seoWordNum'] = intval($res[7]) > 5 ? 5 : intval($res[7]);
        } else {
            $result['seoWordNum'] = 0;
        }

        if (!empty($res[8])) {
            $result['seoWordScale'] = intval($res[8]) > 100 ? 100 : intval($res[8]);
        } else {
            $result['seoWordScale'] = 0;
        }

        if (!empty($res[9])) {
            $result['autonum'] = intval($res[9]) > 5 ? 5 : intval($res[9]);
            $result['autoseo'] = 1;
        } else {
            $result['autonum'] = 0;
            $result['autoseo'] = 0;
        }

        if (!empty($res[10])) {
            $result['autokeywords'] = intval($res[10]) > 5 ? 5 : intval($res[10]);
        } else {
            $result['autokeywords'] = 0;
        }

        if (!empty($res[11])) {
            $result['autotags'] = intval($res[8]) > 5 ? 5 : intval($res[11]);
        } else {
            $result['autotags'] = 0;
        }

        if (!empty($res[12])) {
            $result['baidu_token'] = trim($res[12]);
        }
        
        if (!empty($res[13]) && (trim($res[13])=='是' || trim($res[13])==1)) {
            $result['public_keywords'] = 1;
        }else {
            $result['public_keywords'] = 0;
        }
        
        if (!empty($res[14]) && !empty(15)) {
            $classes = explode(',', $res[14]);
            $pingyin2 = explode(',', $res[15]);
            foreach ($classes as $key => $v) {
                if (!empty($pingyin2[$key]) && check_pingyin($pingyin2[$key])) {
                    $result['classes'][] = ['title' => $v, 'ename' => $pingyin2[$key]];
                }
            }
        }
        return $result;
    }

    protected function checkWebSite($webSite, $row) {
        $res = parse_url($webSite);
        if (empty($webSite) || $res['path'] != $webSite) {
            $this->error[$row][] = '域名格式不符，请检查';
            return false;
        }
        $has_site = db::getField("select count(*) from `yuming` where name='$webSite'");
        if ($has_site > 0) {
            $this->error[$row][] = '域名已存在，不再导入';
            return false;
        }
        return true;
    }

    //任务处理中心
    public function doing() {
        header('X-Accel-Buffering: no'); //关闭输出缓存
        ob_end_flush();
        ob_implicit_flush(true);
        $hasdone = 0;
        $count = 0;
        for ($i = 0; $i <= 1000; $i++) {
            $data = mredis::rPop('queue_improt_yuming');
            if (!empty($data)) {
                try {
                    $data = json_decode($data, true);
                    $res = $this->do_data($data);
                    if ($res) {
                        $count++;
                    }
                } catch (Exception $ex) {
                    continue;
                }
                mac_echo("已成功处理" . $count . "条。");
            } else {
                $hasdone = 1;
                break;
            }
        }
        if ($hasdone == 1) {
            mac_echo('已全部处理完成');
            sleep(3);
            self::redirect("?m=yuming&a=index");
        } else {
            mac_echo('继续进行处理');
            sleep(1);
            header('X-Accel-Buffering: yes'); //关闭输出缓存
            self::redirect("?m=seo&a=import&doing");
        }
    }

    public function test() {
        $data = db::table_exist('words');
    }

    protected function do_data($data) {
        try {
            pdodb::startTrans(); //开启事务
            if ($this->checkWebSite($data['name'], 1)) {
                $template = ['defaultBlack', 'defaultGray', 'defaultRed'];
                $ran_key = array_rand($template, 1);
                $y_insert['name'] = $data['name'];
                $y_insert['description'] = $data['description'];
                $y_insert['sitename'] = $data['sitename'];
                $y_insert['keywords'] = $data['keywords'];
                $y_insert['template'] = $template[$ran_key];
                $y_insert['siteTitle'] = $data['siteTitle'];
                pdodb::insert('yuming', $y_insert);
                $sid = pdodb::insertID();
                if (!empty($sid)) {
                    $classlist = pdodb::getOne('classlist', ['yuming_id' => $sid]);
                    if (empty($classlist)) {
                        foreach ($this->sysclass as $ename => $title) {
                            pdodb::insert('classlist', ['yuming_id' => $sid, 'ename' => $ename, 'title' => $title, 'ifsys' => 1]);
                        }
                    }
                    if (!empty($data['classes'])) {
                        foreach ($data['classes'] as $c) {
                            $c_count = pdodb::getOne('classlist', ['ename' => $c['ename'], 'yuming_id' => $sid], 'COUNT(*) AS num');
                            if ($c_count['num'] == 0) {
                                pdodb::insert('classlist', ['yuming_id' => $sid, 'ename' => $c['ename'], 'title' => $c['title'], 'ifsys' => 1]);
                            }
                        }
                    }
                    //seo优化词插入
                    $v = $data;
                    $r = pdodb::getOne('seoconfig', ['yuming_id' => $sid], '*');
                    $d['seoWordNum'] = $v['seoWordNum'];
                    $d['seoWordScale'] = $v['seoWordScale'];
                    $d['seoTitlex'] = $v['seoTitlex'];
                    $d['seoTitle'] = $v['seoTitle'];
                    $d['autoseo'] = $v['autoseo'];
                    $d['autonum'] = $v['autonum'];
                    $d['autokeywords'] = $v['autokeywords'];
                    $d['autotags'] = $v['autotags'];
                    $d['baidu_token'] = $v['baidu_token'];
                    if ($r) {
                        pdodb::update('seoconfig', $d, ['yuming_id' => $sid]);
                    } else {
                        $d['yuming_id'] = $sid;
                        pdodb::insert('seoconfig', $d);
                    }
                    pdodb::commit();
                    
                    $this->create_tables($sid,$data);
                    return true;
                }
            }
        } catch (Exception $ex) {
            logging_run($ex->getMessage(), 'error','error_run');
            pdodb::rollback();
            return false;
        }
    }

    protected function create_tables($sid,$data) {
        $contentSql = "CREATE TABLE `content_{$sid}` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        `class` varchar(30) DEFAULT NULL,
                        `title` varchar(255) DEFAULT NULL,
                        `flag` char(1) DEFAULT NULL,
                        `source` varchar(50) DEFAULT NULL,
                        `thumb` varchar(255) DEFAULT NULL,
                        `keyword` varchar(255) NOT NULL,
                        `description` varchar(500) DEFAULT NULL,
                        `status` int(11) DEFAULT '0',
                        `click` int(11) DEFAULT '0',
                        `addtime` int(11) DEFAULT '0',
                        `ping_status` int(11) DEFAULT '0',
                        `ping_errMsg` varchar(255) DEFAULT NULL,
                        `seo_keyword` text,
                        `oldtitle` varchar(255) DEFAULT NULL,
                        PRIMARY KEY (`id`),
                        KEY `flag` (`flag`),
                        KEY `title` (`title`),
                        KEY `addtime` (`addtime`),
                        KEY `sycc` (`class`,`flag`,`status`,`addtime`) USING BTREE,
                        KEY `syct` (`class`,`status`,`addtime`) USING BTREE,
                        KEY `oldtitle` (`oldtitle`) USING BTREE
                      ) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8;";

        $taglist_sql = "CREATE TABLE `tagslist_{$sid}` (
                        `id` int(11) NOT NULL AUTO_INCREMENT,
                        `tagsname` varchar(255) DEFAULT NULL,
                        `yuming_id` int(11) DEFAULT NULL,
                        `addtime` int(11) DEFAULT NULL,
                        `click` int(11) NOT NULL DEFAULT '0',
                        PRIMARY KEY (`id`),
                        KEY `tagsname` (`tagsname`),
                        KEY `yuming_id` (`yuming_id`)
                      ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;";
        $tagindex_sql = "CREATE TABLE `tagindex_{$sid}` (
                        `aid` int(11) NOT NULL DEFAULT '0',
                        `tagid` int(11) NOT NULL DEFAULT '0',
                        PRIMARY KEY (`aid`,`tagid`)
                      ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";
        pdodb::query($contentSql);
        pdodb::query($taglist_sql);
        pdodb::query($tagindex_sql);
        if(!empty($data['public_keywords'])) {
            $word_sql = "CREATE TABLE `words_{$sid}` (
                    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
                    `title` varchar(255) NOT NULL DEFAULT '',
                        PRIMARY KEY (`id`),
                        KEY `idx_title` (`title`) USING BTREE
                      ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;";
            pdodb::query($word_sql);
        }
        return true;
    }

}
